//
//  StoreItemAddViewController.m
//  KIASupervisory
//
//  Created by tan_xin on 14-8-17.
//  Copyright (c) 2014年 MyCompany. All rights reserved.
//

#import "StoreItemAddViewController.h"
#import "MTStatusBarOverlay.h"

@interface StoreItemAddViewController () <UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UILabel *dudaoDeptLbl;
@property (weak, nonatomic) IBOutlet UITextField *storeItemNameLbl;
@property (weak, nonatomic) IBOutlet UITextField *storeItemNoteLbl;
@property (weak, nonatomic) IBOutlet UIButton *needFinishBtn;
@property (weak, nonatomic) IBOutlet UIButton *notNeedFinishBtn;
@property (weak, nonatomic) IBOutlet UIButton *needPhotoBtn;
@property (weak, nonatomic) IBOutlet UIButton *notNeedPhotoBtn;

@property (nonatomic, assign) BOOL needFinish;
@property (nonatomic, assign) BOOL needPhoto;

- (IBAction)clickCheckBoxAction:(id)sender;


@end

@implementation StoreItemAddViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.tableView.delegate = self;
    
    self.needFinish = NO;
    self.needPhoto = NO;
    
    [self updateNeedFinishButtonStatus];
    [self updateNeedPhotoButtonStatus];
    
}

- (void)viewWillAppear:(BOOL)animated {
    self.title = @"新增临店项目";
    self.showLeftBtn = YES;
    self.showRightBtn = YES;
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = NO;
    
    [self.leftBtn setBackgroundImage:[UIImage imageNamed:@"Navigationbar_btn_返回_n.png"] forState:UIControlStateNormal];
    [self.leftBtn setBackgroundImage:[UIImage imageNamed:@"Navigationbar_btn_返回_p.png"] forState:UIControlStateHighlighted];
    
    if ([self.erandInfo count] > 0) {
//        NSString *zw = [self.erandInfo objectForKeyOrNil:@"zw"];
//        self.dudaoDeptLbl.text = zw;
        
        NSString *gh = [self.erandInfo objectForKeyOrNil:@"gh"];
        [self getDudaoDeptByGh:gh];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)leftNavItemAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightNavItemAction:(id)sender {
    [self submitNewStoreItem];
}

- (void)getDudaoDeptByGh:(NSString *)gh {
    if ([gh length] == 0) {
        return;
    }
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:gh,@"gh", nil];
    [self.networkManager requestWithMethod:selectZwByGh parameter:param delegate:self];
}

- (void)submitNewStoreItem {
    NSString *itemName = self.storeItemNameLbl.text;
    NSString *itemNote = self.storeItemNoteLbl.text;
    
    if ([itemName length] == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"临店项目内容不能为空，请填写完整"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    } else if ([itemNote length] == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"临店项目简介不能为空，请填写完整"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }  else {
        NSString *dudaoGh = [self.erandInfo objectForKeyOrNil:@"gh"]; //督导工号
        NSString *needFinish = @"";
        NSString *needPhoto = @"";
        if (self.needFinish) {
            needFinish = @"true";
        } else {
            needFinish = @"false";
        }
        if (self.needPhoto) {
            needPhoto = @"true";
        } else {
            needPhoto = @"false";
        }
        NSString *pc = [self.erandInfo objectForKeyOrNil:@"pc"];
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                               pc,@"pc",
                               itemName,@"xmms",
                               itemNote,@"xmmc",
                               needFinish,@"sfbx",
                               needPhoto,@"sfpz",
                               dudaoGh,@"gh", nil];
        [self.networkManager requestWithMethod:addProjectForPc parameter:param delegate:self];
        [self.HUD show:YES];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)updateNeedFinishButtonStatus {
    if (self.needFinish) {
        [self.needFinishBtn setBackgroundImage:[UIImage imageNamed:@"勾选btn_p.png"] forState:UIControlStateNormal];
        [self.notNeedFinishBtn setBackgroundImage:[UIImage imageNamed:@"勾选btn_n.png"] forState:UIControlStateNormal];
    } else {
        [self.needFinishBtn setBackgroundImage:[UIImage imageNamed:@"勾选btn_n.png"] forState:UIControlStateNormal];
        [self.notNeedFinishBtn setBackgroundImage:[UIImage imageNamed:@"勾选btn_p.png"] forState:UIControlStateNormal];
    }
}

- (void)updateNeedPhotoButtonStatus {
    if (self.needPhoto) {
        [self.needPhotoBtn setBackgroundImage:[UIImage imageNamed:@"勾选btn_p.png"] forState:UIControlStateNormal];
        [self.notNeedPhotoBtn setBackgroundImage:[UIImage imageNamed:@"勾选btn_n.png"] forState:UIControlStateNormal];
    } else {
        [self.needPhotoBtn setBackgroundImage:[UIImage imageNamed:@"勾选btn_n.png"] forState:UIControlStateNormal];
        [self.notNeedPhotoBtn setBackgroundImage:[UIImage imageNamed:@"勾选btn_p.png"] forState:UIControlStateNormal];
    }
}

- (IBAction)clickCheckBoxAction:(id)sender {
    UIButton *btn = (UIButton *)sender;
    NSInteger tag = btn.tag;
    if (tag == 100 || tag == 101) { //是否必须完成
        self.needFinish = (tag == 100);
        [self updateNeedFinishButtonStatus];
    } else if (tag == 102 || tag == 103) {
        self.needPhoto = (tag == 102);
        [self updateNeedPhotoButtonStatus];
    }
}

#pragma mark - NetworkManagerDelegate
- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    [self.HUD hide:YES];
    
    if (methodId == selectZwByGh) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            int code = [[data objectForKeyOrNil:@"code"] integerValue];
            if (code == 0) {
                NSString *value = [data objectForKeyOrNil:@"data"];
                if ([value length] > 0) {
                    self.dudaoDeptLbl.text = value;
                } else {
                    if ([self.erandInfo count] > 0) {
                        NSString *zw = [self.erandInfo objectForKeyOrNil:@"zw"];
                        self.dudaoDeptLbl.text = zw;
                    }
                }
            } else {
                if ([self.erandInfo count] > 0) {
                    NSString *zw = [self.erandInfo objectForKeyOrNil:@"zw"];
                    self.dudaoDeptLbl.text = zw;
                }
            }
        }
    } else if (methodId == addProjectForPc) { //新增临店项目
        if ([data isKindOfClass:[NSDictionary class]]) {
            int code = [[data objectForKeyOrNil:@"code"] integerValue];
            if (code == 0) {
                if ([data count] > 0) {
                    id dataObject = [data objectForKeyOrNil:@"data"];
                    if ([dataObject isKindOfClass:[NSDictionary class]]) {
                        NSInteger resultCode = [[dataObject objectForKeyOrNil:@"reslut"] integerValue];
                        if (resultCode == 1) {
//                            MTStatusBarOverlay *overlay = [MTStatusBarOverlay sharedInstance];
//                            overlay.animation = MTStatusBarOverlayAnimationFallDown;
//                            overlay.detailViewMode = MTDetailViewModeDetailText;
//                            overlay.delegate = nil;
//                            overlay.progress = 0.0;
//                            [overlay postFinishMessage:@"新增临店项目成功！" duration:1.6 animated:YES];
//                            overlay.progress = 1.8;
                            
                            [self showAlertViewWithMessage:@"新增临店项目成功"];
                            
                            [self performSelector:@selector(leftNavItemAction:) withObject:nil afterDelay:0.9];
                        }
                    }
                }
                
            } else {
                NSString *msg = [data objectForKeyOrNil:@"msg"];
                if ([msg  length] == 0) {
                    if (methodId == ignoreWorkApply) {
                        msg = @"忽略临店项目失败，请稍后重试";
                    } else if (methodId == deleteProjectById) {
                        msg = @"删除临店项目失败，请稍后重试";
                    }
                }
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                message:msg
                                                               delegate:nil
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
                [alert show];
            }
        }
    }
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFailedWithError:(NSError *)error {
    
    [self.HUD hide:YES];
    
    NSDictionary *errorInfo = error.userInfo;
    NSString *msg = [errorInfo objectForKeyOrNil:@"errorMsg"];
    if ([msg length] == 0) {
        msg = @"新增临店项目失败，请稍后重试";
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                    message:msg
                                                   delegate:nil
                                          cancelButtonTitle:@"确定"
                                          otherButtonTitles:nil];
    [alert show];
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField.inputAccessoryView == nil) {
        UIToolbar * topView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 30)];
        [topView setBarStyle:UIBarStyleDefault];
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(CGRectGetWidth(self.view.bounds)-42, 3, 40, 26);
        [button setTitle:@"完成" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button.titleLabel setFont:[UIFont systemFontOfSize:14]];
        [button addTarget:self action:@selector(dismissKeyBoard:) forControlEvents:UIControlEventTouchUpInside];
        
        [topView addSubview:button];
        
        [textField setInputAccessoryView:topView];
    }
    return YES;
}

- (void)dismissKeyBoard:(id)sender {
    [self.view endEditing:YES];
}

@end
